package com.ggb.reactive.task

import com.ggb.reactive.constant.MessageConstant
import com.ggb.reactive.constant.OrderStatus
import com.ggb.reactive.extension.log
import com.ggb.reactive.service.OrderService
import lombok.RequiredArgsConstructor
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.Instant
import java.time.ZoneId

@Component
@RequiredArgsConstructor
class OrderTask(
    val orderService: OrderService
) {
    /**
     * 处理超时订单的方法
     */
    @Scheduled(cron = "0 * * * * ?") //每分钟执行一次
    fun processTimeoutOrder() {
        val now = Instant.now().atZone(ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("GMT+8")).toLocalDateTime()
        log.info("定时处理超时订单：{}", now)
        println("定时处理超时订单：$now")
        val time = Instant.now().plusSeconds(-15 * 60)
        orderService.getByStatusAndOrderTimLT(OrderStatus.PENDING_PAYMENT.getStatus(), time)
            .flatMap { order ->
                order.apply {
                    status = OrderStatus.CANCELLED.getStatus()
                    cancelReason = MessageConstant.ORDER_TIMEOUT_MSG
                    cancelTime = Instant.now()
                }
                orderService.updateOrder(order)
            }
            .subscribe()
    }
    /**
     * 处理超时订单的方法
     */
    @Scheduled(cron="0 0 1 * * ?") // 每天凌晨1点执行
    fun processDeliveryOrder(){
        log.info("定时处理配送中的订单：{}", Instant.now());
        val time = Instant.now().plusSeconds(-15*60)
        orderService.getByStatusAndOrderTimLT(OrderStatus.PENDING_PAYMENT.getStatus(),time)
            .flatMap {
                it.apply {
                    status = OrderStatus.COMPLETED.getStatus()
                }
                orderService.updateOrder(it)
            }
            .subscribe()
    }
}